package com.jpa.demo.example;

import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.util.List;

@Service
public class UserService {

    /**
     * @PersistenceContext 为每个事务提供独立的EntityManager，相当于@Autowired但是避免了事务管理、线程安全问题的问题
     * 交由spring进行管理，不需要手动创建工厂类和EntityManager
     * 注入的是EntityManager的代理对象
     * Shared EntityManager proxy for target factory [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean@470c4229]
     */
    @PersistenceContext
    private EntityManager entityManager;

    @Transactional
    public void createUser(String name) {
        User user = new User(name);
        entityManager.persist(user);
    }

    public User findUser(Long id) {
        return entityManager.find(User.class, id);
    }

    @Transactional
    public User updateUser(Long id, String newName) {
        User user = entityManager.find(User.class, id);
        if (user != null) {
            user.setName(newName);
            return entityManager.merge(user);
        }
        return null;
    }

    @Transactional
    public void deleteUser(Long id) {
        User user = entityManager.find(User.class, id);
        if (user != null) {
            entityManager.remove(user);
        }
    }

    public List<User> findAllUsers() {
        return entityManager.createQuery("SELECT u FROM User u", User.class).getResultList();
    }
}
